#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :app.py
# @Time      :2025/2/14 16:43
# @Author    :kk
from flask import Flask, session, g
from flask import render_template
from flask import request
from flask import redirect
from flask import url_for
from mongoengine import connect

import config
from exts import db, mail, redis_client, mongo
from blueprints.qa import bp as qa_bp
from blueprints.auth import bp as auth_bp
from blueprints.article import bp as article_bp

from models import UserModel
from flask_migrate import Migrate

app = Flask(__name__)
# 绑定配置文件
app.config.from_object(config)

db.init_app(app)
mail.init_app(app)
redis_client.init_app(app)
# 连接到 MongoDB
mongo.init_app(app)


migrate = Migrate(app,db)

app.register_blueprint(qa_bp)
app.register_blueprint(auth_bp)
app.register_blueprint(article_bp)

# blueprint: 用来做模块化的
# 电影、读书、音乐

# before_request: 在请求之前执行，可以做权限验证，日志记录等
# before_first_request: 在第一次请求之前执行，可以做初始化操作
# after_request: 在请求之后执行，可以做日志记录等
# error_handler: 错误处理
@app.before_request
def my_before_request():
    user_id = session.get("user_id")
    if user_id :
        print(f"》》》》》{user_id}")
        user = UserModel.query.filter_by(id=user_id).first()
        if user:
            setattr(g,"user",user)
        else:
            setattr(g,"user",None)
    else:
        setattr(g,"user",None)

@app.context_processor
def my_context_processor():
    return {"user":g.user}

if __name__ == "__main__":
    app.run(debug=True)
